import React, { Component } from "react";
import Layout from "../../components/layout/MyLayout";
import Markdown from "react-markdown";
import { getArticleById } from "../../redux/actions";
import { connect } from "react-redux";
import HeadingBlock from "../../components/markdown/HeadingBlock";
import { Affix, BackTop, Button, Comment, Icon, Tooltip, Avatar, Divider, Form, Input, Skeleton } from "antd";
import uuid from "react-uuid";
import moment from "moment";
import Router, { withRouter } from "next/router";

const { TextArea } = Input;

@connect(
  ({ article }) => {
    return { article };
  },
  { getArticleById }
)
class Article extends Component {
  constructor(props) {
    super(props);
    this.state = {
      markdown: "",
      menus: [],
      likes: 0,
      dislikes: 0,
      action: null,
      comments: [],
      submitting: false,
      value: "",
      SkeletonLoading: true
    };

    this.like = () => {
      this.setState({
        likes: 1,
        dislikes: 0,
        action: "liked"
      });
    };

    this.dislike = () => {
      this.setState({
        likes: 0,
        dislikes: 1,
        action: "disliked"
      });
    };

    this.handleSubmit = () => {
      if (!this.state.value) {
        return;
      }
    };
  }

  async componentDidMount() {
    await this.props.getArticleById({ id: this.props.router.query.curArticleId });

    this.setState({ SkeletonLoading: false }, () => {
      const linkArr = document.querySelectorAll(".markdown-body .quick-link");

      if (linkArr && linkArr.length > 0) {
        let menus = [];
        linkArr.forEach(item => {
          menus.push({
            name: item.name,
            level: item.getAttribute("level").replace(/^h/, "")
          });
        });
        this.setState({ menus });
      }
    });
  }

  renderStyle(level) {
    let style = {};
    style.marginLeft = `${10 * level}px`;
    Number(level) <= 2 ? (style.fontSize = "14px") : (style.fontSize = "10px");
    return style;
  }

  render() {
    const { article } = this.props;
    const { menus, likes, dislikes, action, submitting, value, SkeletonLoading } = this.state;

    const actions = [
      <span key="comment-basic-like">
        <Tooltip title="Like">
          <Icon type="like" theme={action === "liked" ? "filled" : "outlined"} onClick={this.like} />
        </Tooltip>
        <span style={{ paddingLeft: 8, cursor: "auto" }}>{likes}</span>
      </span>,
      <span key=' key="comment-basic-dislike"'>
        <Tooltip title="Dislike">
          <Icon type="dislike" theme={action === "disliked" ? "filled" : "outlined"} onClick={this.dislike} />
        </Tooltip>
        <span style={{ paddingLeft: 8, cursor: "auto" }}>{dislikes}</span>
      </span>,
      <span key="comment-basic-reply-to">Reply to</span>
    ];

    const Editor = ({ onChange, onSubmit, submitting, value }) => (
      <div>
        <Form.Item>
          <TextArea rows={4} onChange={onChange} value={value} />
        </Form.Item>
        <Form.Item>
          <Button htmlType="submit" loading={submitting} onClick={onSubmit} type="primary">
            Add Comment
          </Button>
        </Form.Item>
      </div>
    );

    return (
      <Layout>
        <div className="book-detail">
          <div className="markdown-banner">
            <img src="../../static/images/article-banner.jpg" alt="banner" />
          </div>
          <div className="markdown ">
            <Skeleton loading={SkeletonLoading} paragraph={{ rows: 20 }} active>
              <Markdown
                className="markdown-body"
                source={article && article.markdown}
                renderers={{
                  heading: HeadingBlock
                }}
              />
            </Skeleton>
            <Divider>评论</Divider>
            <Comment
              actions={actions}
              author={<a>诶嘿嘿</a>}
              avatar={
                <Avatar
                  src=""
                  alt="Han Solo"
                />
              }
              content={
                <p>
                  红勤奋学习，每天手不释卷，看见优美的文章，总是目不转睛地盯着看，因此她的学习成绩在班上遥遥领先，常常受到老师的夸奖.
                </p>
              }
              datetime={
                <Tooltip title={moment().format("YYYY-MM-DD HH:mm:ss")}>
                  <span>{moment().fromNow()}</span>
                </Tooltip>
              }
            />
            <Divider>回复</Divider>
            <Comment
              avatar={
                <Avatar
                  src="https://images.xiaozhuanlan.com/photo/2019/2ad6384db0b94cd8e76d11194400df23.jpeg"
                  alt="Han Solo"
                />
              }
              content={
                <Editor
                  onChange={this.handleChange}
                  onSubmit={this.handleSubmit}
                  submitting={submitting}
                  value={value}
                />
              }
            />
          </div>

          {/* 右侧快捷导航 */}
          <div className="markdown-menu-outer">
            <Affix offsetTop={30}>
              <Skeleton loading={SkeletonLoading} paragraph={{ rows: 10 }} active>
                <div className="markdown-menu">
                  <ul>
                    {menus &&
                      menus.map(item => {
                        return (
                          <li key={uuid()} style={this.renderStyle(item.level)}>
                            <a name={item.name} href={`#${item.name}`}>
                              {item.name}
                            </a>
                          </li>
                        );
                      })}
                  </ul>
                </div>
              </Skeleton>
            </Affix>
          </div>

          <BackTop>
            <Button type="primary" icon="arrow-up" alt="返回顶部" />
          </BackTop>

          <style jsx global>{`
            .markdown a {
              text-decoration: none;
              color: blue;
            }

            .markdown a:hover {
              opacity: 0.6;
            }

            .markdown h3 {
              margin: 0;
              padding: 0;
              text-transform: uppercase;
            }
          `}</style>
          <style jsx>{`
            .book-detail {
              width: 1000px;
              height: 100%;
              margin: 0 auto;
              padding: 30px 0;
            }

            .markdown {
              float: left;
              font-family: "Arial";
              width: 750px;
              padding: 30px 0 30px 0;
            }

            .markdown-menu-outer {
              float: right;
              width: 230px;
              padding: 30px 0 30px 0;
            }

            .markdown-menu {
              max-height: calc(100vh - 60px);
              min-height: 30px;
              overflow: auto;
            }

            .markdown-menu a {
              color: #666;
            }

            .markdown-menu a:hover {
              color: #1890ff;
            }

            .markdown-menu li {
              list-style: disc;
              font-weight: 600;
              line-height: 28px;
              cursor: pointer;
            }

            .markdown-banner {
              width: 100%;
            }

            .markdown-banner img {
              width: 100%;
            }
          `}</style>
        </div>
      </Layout>
    );
  }
}

export default withRouter(Article);
